package com.pengpai.pangucms.config;

import com.pengpai.pangucms.filter.CaptchaFilter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Slf4j
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {


    @Resource
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

        //白名单路径
        String[] urls = ignoreUrlsConfig.getUrls().toArray(new String[0]);

        return httpSecurity
                //以下是验证请求拦截和放行配置
                .authorizeHttpRequests(auth -> {
                    auth.requestMatchers(urls).permitAll();
                    auth.anyRequest().authenticated();    //将所有请求全部拦截，一律需要验证
                })
                //以下是表单登录相关配置
                .formLogin(conf -> {
                    conf.loginPage("/login");   //将登录页设置为我们自己的登录页面
                    conf.loginProcessingUrl("/login"); //登录表单提交的地址，可以自定义
                    conf.defaultSuccessUrl("/",true);   //登录成功后跳转的页面
                    conf.failureUrl("/login?error=true");
                    conf.permitAll();    //将登录相关的地址放行，否则未登录的用户连登录界面都进不去
                })
                .logout(conf ->{
                    conf.logoutUrl("/logout");
                    conf.deleteCookies("JESSIONID");
                    conf.permitAll();
                })
                .addFilterBefore(new CaptchaFilter(), UsernamePasswordAuthenticationFilter.class)
                .csrf(AbstractHttpConfigurer::disable)
                .headers(AbstractHttpConfigurer::disable)
                .build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/static/**");
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


}
